package wqldistinctlocktest.distinctlock.service.Impl;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wqldistinctlocktest.distinctlock.dao.StockDao;
import wqldistinctlocktest.distinctlock.entity.Stock;
import wqldistinctlocktest.distinctlock.service.StockService_redission;

import java.util.concurrent.TimeUnit;

/**
 * @author wql
 * @version 1.0
 * @date 2022/12/8 18:02
 */
@Service
public class StockService_redissionImpl implements StockService_redission {
    @Autowired
    private StockDao stockDao;
    @Autowired
    private RedissonClient redisson;

    @Override
    public String decrement(Integer productid) {
        //获取锁对象
        RLock lock = redisson.getLock("product::" + productid);
        //一定要设置为30秒
        lock.lock(30, TimeUnit.SECONDS);
        try {
            Stock stock = stockDao.selectById(productid);
            if (stock.getStock() > 0) {
                stock.setStock(stock.getStock() - 1);
                stockDao.updateById(stock);
                System.out.println("商品编号为:" + productid + "的商品库存剩余:" + stock.getStock() + "个");
                return "商品编号为:" + productid + "的商品库存剩余:" + stock.getStock() + "个";
            } else {
                System.out.println("商品编号为:" + productid + "的商品库存不足。");
                return "商品编号为:" + productid + "的商品库存不足。";
            }
        } finally {
            //释放
            lock.unlock();
        }

    }
}
